using System.Collections.Specialized;
using System.ComponentModel.Design;
using EnvDTE;
using Microsoft.Practices.Common;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Extensions.CommonHelpers;
using Microsoft.Practices.RecipeFramework.Library;

namespace PrismFactory.SoftwareFactory.Extensions.ValueProviders.VisualStudio
{
    [ServiceDependency(typeof (DTE))]
    public class ProjectByNameExpressionProvider : ValueProvider, IAttributesConfigurable
    {
        private string nameExpression;

        #region Overrides

        /// <summary>
        /// Uses <see cref="DteHelper.FindProjectByPath"/> to search for the project specified by the "Path" attributte
        /// </summary>
        /// <param name="currentValue"></param>
        /// <param name="newValue"></param>
        /// <returns></returns>
        /// <seealso cref="ValueProvider.OnBeginRecipe"/>
        /// <seealso cref="DteHelper.FindProjectByPath"/>
        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            var dte = (DTE) GetService(typeof (DTE));
            var dictservice = (IDictionaryService) GetService(typeof (IDictionaryService));

            if (currentValue == null)
            {
                var projectName = ExpressionEvaluationHelper.EvaluateExpression(dictservice, nameExpression) as string;

                newValue = DteHelperEx.FindProjectByName(dte, projectName, false);
                if (newValue != null)
                {
                    return true;
                }
            }
            newValue = currentValue;
            return false;
        }

        /// <param name="currentValue"></param>
        /// <param name="newValue"></param>
        /// <returns></returns>
        /// <seealso cref="ValueProvider.OnBeforeActions"/>
        /// <seealso cref="OnBeginRecipe"/>
        public override bool OnBeforeActions(object currentValue, out object newValue)
        {
            return OnBeginRecipe(currentValue, out newValue);
        }

        #endregion

        #region IAttributesConfigurable Members

        void IAttributesConfigurable.Configure(StringDictionary attributes)
        {
            nameExpression = attributes["NameExpression"];
        }

        #endregion
    }
}